<script setup name="content">
import { reactive, ref } from "vue"
import { toast } from "@/composables/util"
import { readGoods, updateGoodsSkus } from "@/api/goods"
import { initSkuCardList, goodsId, skus_list } from "@/composables/useSku"
import FormDialog from "@/components/FormDialog.vue"
import SkuCard from "./SkuCard.vue"
import SkuTable from "./SkuTable.vue"

// 表单数据
const form = reactive({
  sku_type: 0,
  sku_value: {
    oprice: 0,
    pprice: 0,
    cprice: 0,
    weight: 0,
    volume: 0
  }
})
// 加载
const loading = ref(false)
// 当前商品id
const dialogRef = ref(null)
const emit = defineEmits(["reload"])

// 显示对话框
const open = async row => {
  goodsId.value = row.id
  loading.value = true
  dialogRef.value.open()
  const res = await readGoods(goodsId.value)
  form.sku_type = res.sku_type
  form.sku_value = res.sku_value || {
    oprice: 0,
    pprice: 0,
    cprice: 0,
    weight: 0,
    volume: 0
  }
  initSkuCardList(res)
  loading.value = false
}
// 提交
const submit = async () => {
  let data = {
    sku_type: form.sku_type,
    sku_value: form.sku_value
  }
  if (form.sku_type === 1) {
    data.goodsSkus = skus_list.value
  }
  try {
    dialogRef.value.showLoading()
    await updateGoodsSkus(goodsId.value, data)
    console.log(form)
    toast("设置商品规格成功！")
    emit("reload")
    dialogRef.value.close()
  } finally {
    dialogRef.value.hideLoading()
  }
}
// 向外导出方法
defineExpose({ open })
</script>

<template>
  <FormDialog class="skus-dialog" ref="dialogRef" title="设置商品规格" top="5vh" :width="80" @submit="submit" destroy-on-close>
    <el-form :model="form" v-loading="loading" label-width="68px">
      <el-form-item label="规格类型">
        <el-radio-group v-model="form.sku_type">
          <el-radio :label="0">单规格</el-radio>
          <el-radio :label="1">多规格</el-radio>
        </el-radio-group>
      </el-form-item>
      <template v-if="form.sku_type === 0">
        <el-form-item label="市场价格">
          <el-input v-model="form.sku_value.oprice">
            <template #append>元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="销售价格">
          <el-input v-model="form.sku_value.pprice">
            <template #append>元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="成本价格">
          <el-input v-model="form.sku_value.cprice">
            <template #append>元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="商品重量">
          <el-input v-model="form.sku_value.weight">
            <template #append>公斤</template>
          </el-input>
        </el-form-item>
        <el-form-item label="商品体积">
          <el-input v-model="form.sku_value.volume">
            <template #append>立方米</template>
          </el-input>
        </el-form-item>
      </template>
      <template v-else>
        <SkuCard />
        <SkuTable />
      </template>
    </el-form>
  </FormDialog>
</template>

<style lang="scss" scoped></style>
